package com.googlecode.stemwijzer.server;

import com.google.inject.Inject;
import com.googlecode.stemwijzer.client.StemwijzerService;
import com.googlecode.stemwijzer.server.session.ServerSession;
import com.googlecode.stemwijzer.shared.NameValidator;
import com.googlecode.stemwijzer.shared.model.IsAnswer;
import com.googlecode.stemwijzer.shared.model.IsQuestion;
import com.googlecode.stemwijzer.shared.model.IsQuestionnaireResult;

public class DefaultStemwijzerService implements StemwijzerService {

	/** Session reference to keep state. */
	protected ServerSession session;

	@Inject
	public DefaultStemwijzerService(final ServerSession session) {
		this.session = session;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.googlecode.stemwijzer.client.StemwijzerService#getResult()
	 */
	@Override
	public IsQuestionnaireResult getResult() {
		System.out.println("Getting questionnaire result");
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.googlecode.stemwijzer.client.StemwijzerService#registerUser(java.lang.String)
	 */
	@Override
	public Boolean registerUser(final String userName) {
		System.out.println("Registering username [" + userName + "]");

		if (!NameValidator.isValid(userName)) {
			return null;
		}
		this.session.setUserName(userName);
		this.session.reset();

		return true;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.googlecode.stemwijzer.client.StemwijzerService#resetSession()
	 */
	@Override
	public Boolean resetSession() {
		System.out.println("Resetting session");

		if (this.session == null) {
			this.session = new ServerSession();
		} else {
			this.session.reset();
		}
		return true;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.googlecode.stemwijzer.client.StemwijzerService#sendAnswer(com.googlecode.stemwijzer.shared.model.impl.Answer)
	 */
	@Override
	public Boolean sendAnswer(final IsQuestion question, final IsAnswer answer) {
		System.out.println("Sending answer");

		if (this.session == null) {
			return false;
		}
		if ((question == null) || (answer == null)) {
			return false;
		}

		this.session.setAnswer(question, answer);

		return true;
	}
}
